<template>
  <div class="app-container">
    <el-row>
      <el-col>
        <el-select v-model="queryParams.year" placeholder="选择年份" @change="handleYearChange">
          <el-option v-for="item in dict.type.biz_work_year_list" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
        <el-select v-model="queryParams.quarter" placeholder="选择季度" class="ml-10" @change="handleQuarterChange">
          <el-option v-for="item in quarterOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
      </el-col>
    </el-row>
    <div class="text-banner">
      <span>待审批重点工作</span>
      <el-button size="mini" type="primary" circle icon="el-icon-refresh" plain @click="handleRefresh" />
    </div>

    <el-collapse v-model="queryParams.deptId" @change="handleCollapseChange" accordion v-if="deptOptions.length">
      <el-collapse-item v-for="item in deptOptions" :key="item.value" :title="item.label" :name="item.value">
        <template slot="title">
          <div class="collapse-title">
            <span>{{ item.label }}</span>
            <!-- <span>（共 {{ keyWorkTotal || 0 }} 条）</span> -->
          </div>
        </template>

        <el-card v-loading="keyWorkLoading" :body-style="{ 'padding-top': 0 }">
          <div v-for="(keyWork, index) in keyWorkList" :key="keyWork.month">
            <div class="month-title">
              <p>
                <span class="month-mark-first">{{ keyWork.month }}</span>
                <span>月份重点工作</span>
                <!-- <span class="ml-20">共计</span><span class="month-mark-second">{{ keyWorkMaxScore }}</span> 分， 已分配
            <span class="month-mark-second">{{ keyWork.score }}</span>
            分， 剩余<span class="month-mark-second">{{ keyWorkMaxScore - keyWork.score }}</span
            >分 -->
              </p>
              <div>
                <el-button
                  size="mini"
                  type="primary"
                  plain
                  icon="el-icon-menu"
                  :disabled="keyWork.disabled"
                  @click="handleBatchApproval('pass', keyWork, index)"
                >
                  批量通过
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                  plain
                  icon="el-icon-menu"
                  :disabled="keyWork.disabled"
                  @click="handleBatchApproval('reject', keyWork, index)"
                >
                  批量退回
                </el-button>
              </div>
            </div>
            <div>
              <el-table :data="keyWork.list" border style="width: 100%" @selection-change="handleSelectionChange($event, index)">
                <el-table-column type="selection" width="55"> </el-table-column>
                <el-table-column label="序号" type="index" align="center">
                  <template slot-scope="scope">
                    <span>{{ scope.$index + 1 }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="normName" label="指标名称" width="180" align="center"> </el-table-column>
                <!-- <el-table-column prop="workNatureDict" label="工作性质" width="180" align="center">
                  <template slot-scope="scope">
                    <dict-tag :options="dict.type.biz_work_nature" :value="scope.row.workNatureDict" />
                  </template>
                </el-table-column> -->
                <el-table-column prop="workContent" label="内容及方式" min-width="180" align="center">
                  <template slot-scope="scope">
                    <div class="pre-wrap align-left">{{ scope.row.workContent || '-' }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="planScore" label="分值" width="120" align="center"> </el-table-column>
                <el-table-column prop="workCreateDate" label="创建日期" width="160" align="center"> </el-table-column>
                <el-table-column prop="name" label="操作" align="center" width="130" fixed="right">
                  <template slot-scope="scope">
                    <!-- <el-popover placement="top-end" trigger="hover" v-show="checkBtnVisible('finish', scope.row.workAuditStatusDict)">
                  <div v-html="aduitContentFormat(scope.row)"></div>
                  <el-button type="text" slot="reference" size="mini" class="color-success" icon="el-icon-check">[审核通过]</el-button>
                </el-popover> -->

                    <ApprovalLog :biz-id="scope.row.id" placement="bottom-end">
                      <el-button type="text" size="mini" @click.stop="handleApproval(scope.row, 'pass')" v-hasPermi="['approval:keywork:pass']">
                        通过
                      </el-button>
                    </ApprovalLog>
                    <ApprovalLog :biz-id="scope.row.id" placement="bottom-end">
                      <el-button
                        type="text"
                        size="mini"
                        @click.stop="handleApproval(scope.row, 'reject')"
                        class="color-danger ml-10"
                        v-hasPermi="['approval:keywork:reject']"
                      >
                        退回
                      </el-button>
                    </ApprovalLog>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-card>
      </el-collapse-item>
    </el-collapse>

    <el-empty v-else v-loading="keyWorkLoading" :image-size="200" description="暂无待审批数据"></el-empty>
  </div>
</template>

<script>
import { approval, approvalList as listPlan } from '@/api/work-approval'
import { listDept } from '@/api/work'
import { quarterFormat, quarterToMonth } from '@/utils/quarter.js'
import { getDicts } from '@/api/system/dict/data.js'
import ApprovalLog from '@/components/ApprovalLog'
export default {
  name: 'key-work',
  dicts: ['biz_work_year_list', 'biz_work_nature', 'biz_work_score_type'],
  props: {},
  components: { ApprovalLog },
  data() {
    return {
      keyWorkTotal: 0,
      keyWorkList: [],
      keyWorkMaxScore: 0, // 重点工作最大分值
      keyWorkLoading: false,
      quarterOptions: [],
      deptOptions: [],
      queryParams: {
        year: '',
        quarter: '',
        workType: 'ZDGZ',
        deptId: ''
      },
      selectionList: []
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getWorkScore()
    this.handleYearChange(new Date().getFullYear())
  },
  methods: {
    handleCollapseChange(val) {
      this.getList()
    },
    // 校验表格是否禁选
    checkSelectable(raw, index) {
      if (raw.workAuditStatusDict !== 'DSH') {
        return false
      }
      return true
    },
    // 表格多选
    handleSelectionChange(selection, index) {
      this.selectionList[index] = selection
      // 校验批量选择状态
      if (selection.length) {
        this.$set(this.keyWorkList[index], 'disabled', false)
      } else {
        this.$set(this.keyWorkList[index], 'disabled', true)
      }
    },
    // 批量审批
    handleBatchApproval(operation, raw, index) {
      let auditRemark = '同意'
      let workAuditStatusDict = 'SHTG'
      if (operation === 'reject') {
        auditRemark = '不同意'
        workAuditStatusDict = 'SHBTG'
      }
      let params = this.selectionList[index].map(item => {
        return { id: item.id, auditRemark, workAuditStatusDict }
      })
      let content = `您正在审批 【${raw.month}月份】已选中的 ${this.selectionList[index].length} 项工作，请输入审批意见`
      this.approvalPrompt(operation, content, auditRemark, params)
    },

    // 审批操作
    handleApproval(raw, operation) {
      let params = { id: raw.id, workAuditStatusDict: 'SHTG', auditRemark: '同意' }
      if (operation === 'reject') {
        params.workAuditStatusDict = 'SHBTG'
        params.auditRemark = '不同意'
      }
      let content = `您正在审批 【${raw.month}月份-${raw.normName}】 工作项，请输入审批意见`
      this.approvalPrompt(operation, content, params.auditRemark, [params])
    },
    // 审批窗口
    approvalPrompt(operation, content, inputValue, params) {
      this.$prompt(content, '审批提醒', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '输入审批意见',
        inputType: 'textarea',
        inputPattern: /\S/,
        inputValue: inputValue,
        inputErrorMessage: '审批意见不能为空',
        beforeClose: (action, instance, done) => {
          params.forEach(item => {
            item.auditRemark = instance.inputValue
          })
          if (action === 'confirm') {
            const loading = this.$loading({
              target: '.el-message-box',
              lock: true,
              text: '数据处理中',
              spinner: 'el-icon-loading',
              background: 'rgba(255,255,255,0.6)'
            })
            approval(params)
              .then(() => {
                loading.close()
                if (operation === 'pass') {
                  this.$modal.msgSuccess('已通过')
                } else if (operation === 'reject') {
                  this.$modal.msgError('已退回')
                }
                this.handleRefresh()
                done()
              })
              .catch(() => {
                loading.close()
                done()
              })
          } else {
            done()
          }
        }
      })
    },
    // 刷新
    handleRefresh() {
      this.getDeptList()
    },
    // 获取待审批部门
    getDeptList() {
      let params = JSON.parse(JSON.stringify(this.queryParams))
      delete params.deptId
      listDept(params).then(res => {
        let { data } = res
        if (Array.isArray(data) && data.length) {
          this.deptOptions = res.data.map(item => {
            return { label: item.deptName, value: item.deptId }
          })
          let findDept = this.deptOptions.find(item => item.deptId === this.queryParams.deptId)
          if (!findDept) {
            this.queryParams.deptId = this.deptOptions[0].value
          }
        } else {
          this.deptOptions = []
          this.queryParams.deptId = ''
        }
        this.getList()
      })
    },
    // 审核提示内容格式输出
    aduitContentFormat(raw) {
      let content = []
      if (raw.auditRemark) {
        content.push(`<p style='max-width:300px'>最近审核意见：${raw.auditRemark || ' - '}</p>`)
        content.push(`<p style='max-width:300px'>最近审核时间：${raw.auditTime || ' - '}</p>`)
        return content.join('')
      }
      return false
    },
    // 校验按钮显示
    // 操作类型、审核状态
    checkBtnVisible(type, audit) {
      switch (type) {
        case 'pass': // 通过
        case 'reject': // 退回
          return audit === 'DSH'
        case 'finish': // 审核已完成
          return audit === 'SHTG'
        default:
          return false
      }
    },
    // 重点工作已使用分值
    keyWorkUsedScore(month) {
      const index = this.keyWorkList.findIndex(item => item.month == month)
      const sum = this.keyWorkList[index].list.reduce((prev, curr) => {
        if (curr.planScore) {
          return prev + parseInt(curr.planScore)
        } else {
          return prev
        }
      }, 0)
      this.$set(this.keyWorkList[index], 'score', sum)
    },
    // 获取工作分数限制
    getWorkScore() {
      getDicts('biz_dept_norm_config').then(res => {
        let { data } = res
        this.keyWorkMaxScore = data.find(item => item.dictValue === 'ZDGZ')?.remark
      })
    },
    // 年度选择
    handleYearChange(year) {
      this.queryParams.year = year
      // 获取当前季度、季度列表（往年默认第一季度）
      let { quarter, quarterList } = quarterFormat(year)
      this.quarterOptions = quarterList
      this.handleQuarterChange(quarter)
    },
    // 季度选择
    handleQuarterChange(quarter) {
      this.queryParams.quarter = quarter
      // 获取季度对应月份
      this.keyWorkList = quarterToMonth(quarter).map(month => {
        return { month, score: 0, list: [], disabled: true }
      })
      this.handleRefresh()
    },
    getList() {
      this.getKeyWorkList()
    },
    // 重点工作列表
    getKeyWorkList() {
      this.keyWorkLoading = true
      listPlan(this.queryParams)
        .then(res => {
          this.keyWorkLoading = false

          let { data, total } = res
          this.keyWorkTotal = data.length
          // 筛选季度对应月份数据
          this.keyWorkList.forEach((item, index) => {
            this.keyWorkList[index].list = data.filter(work => item.month == work.month)
            // 获取到列表数据手动计算值情况
            // this.keyWorkUsedScore(this.keyWorkList[index].month)
          })
        })
        .catch(err => (this.keyWorkLoading = false))
    }
  }
}
</script>

<style lang="scss" scoped>
@import url('~@/assets/styles/work.scss');
::v-deep .el-button--text [class*='el-icon-'] + span {
  margin-left: 0;
}
.collapse-title {
  font-size: 16px;
  font-weight: 600;
  padding-left: 20px;
}
</style>
